/**
 * version 1.4
 */
import umcons from './constant.js';
import request from './request.js';
//prod环境
const baseUrl = "https://xxx.com/";
//dev环境
//const baseUrl = "https://test.xxx.com/"
//字节防抖
var timer = null;
let delay = 500;
//刷新处理
function setRefresh(refresh) {
	if (refresh == 1) {
		uni.stopPullDownRefresh();
	}
}
/**
 * 显示异常
 * @param {Object} msg
 */
function showToast(msg) {
	uni.showToast({
		title: msg,
		mask: true,
		duration: 1000
	});
	setTimeout(function() {
		uni.hideToast();
	}, 2000);
}
export default {
	/**
	 * post 请求
	 * @param {Object} url 请求地址后缀
	 * @param {Object} params  请求参数
	 * @param {Object} refresh 是否刷新
	 * @param {Object} callback 请求响应
	 * @param {Object} context 请求上下文
	 */
	seedPost(url, params, refresh, callback) {
		var headers = {
			token: uni.getStorageSync('token'),
			'Content-Type': "application/x-www-form-urlencoded"
		};
		if(refresh==1){
			delay=1000;
		}
		if(timer!=null){
			clearTimeout(timer);
		}
		timer = setTimeout(function() {
			request.post(baseUrl + url, params, headers, function(data) {
				callback(data.data, data.code, data.msg);
				setRefresh(refresh);
			}, function(code, msg) {
				if (code == 1001) {
					showToast(msg);
				} else {
					callback(null, code, msg);
				}
				setRefresh(refresh);
			});
		}, delay);

	},
	/**
	 * get 请求
	 * @param {Object} url 请求地址后缀
	 * @param {Object} params  请求参数
	 * @param {Object} refresh 是否刷新
	 * @param {Object} callback 请求响应
	 * @param {Object} context 请求上下文
	 */
	seedGet(url, params, refresh, callback) {
		var headers = {
			token: uni.getStorageSync('token'),
			'Content-Type': "application/x-www-form-urlencoded"
		};
		if(refresh==1){
			delay=1000;
		}
		if(timer!=null){
			clearTimeout(timer);
		}
		timer = setTimeout(function() {
			request.get(baseUrl + url, params, headers, function(data) {
				callback(data.data, data.code, data.msg);
				setRefresh(refresh);
			}, function(code, msg) {
				if (code == 1001) {
					showToast(msg);
				} else {
					callback(null, code, msg);
				}
				setRefresh(refresh);
			});
		}, delay);
	}
};
